package view

import (
	"cloudops/src/common"
	"cloudops/src/config"
	"cloudops/src/models"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/go-playground/validator/v10"
	"go.uber.org/zap"
	"strconv"
)

func createJobExecScript(c *gin.Context) {
	sc := c.MustGet(common.GIN_CTX_CONFIG_CONFIG).(*config.ServerConfig)
	var reqObj models.JobScript
	err := c.ShouldBindJSON(&reqObj)
	if err != nil {
		sc.Logger.Error("解析新增脚本模板请求失败", zap.Any("脚本模板", reqObj), zap.Error(err))
		common.FailWithMessage(err.Error(), c)
		return
	}

	//字段校验
	err = validate.Struct(reqObj)
	if err != nil {
		if errors, ok := err.(*validator.ValidationErrors); ok {
			common.ReqBadFailWithWithDetailed(
				gin.H{
					"翻译前": errors.Error(),
					"翻译后": errors.Translate(trans),
				},
				"请求出错",
				c,
			)
			return
		}
		common.FailWithMessage(err.Error(), c)
		return
	}
	userName := c.MustGet(common.GIN_CTX_JWT_USER_NAME).(string)
	dbUser, err := models.GetUserByUserName(userName)
	if err != nil {
		sc.Logger.Error("获取用户失败", zap.Any("用户名", userName), zap.Error(err))
		common.FailWithMessage(err.Error(), c)
		return
	}
	reqObj.UserID = dbUser.ID

	// 创建脚本
	err = reqObj.JobScriptCreate()
	if err != nil {
		sc.Logger.Error("创建脚本失败", zap.Any("脚本模板", reqObj), zap.Error(err))
		common.FailWithMessage(err.Error(), c)
		return
	}
	common.OkWithMessage("创建脚本成功", c)
}

func getJobExecScriptList(c *gin.Context) {
	sc := c.MustGet(common.GIN_CTX_CONFIG_CONFIG).(*config.ServerConfig)
	currentPage, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	pageSize, _ := strconv.Atoi(c.DefaultQuery("pageSize", "100"))

	searchUserID := c.DefaultQuery("UserID", "")
	searchUserIDInt, _ := strconv.Atoi(searchUserID)
	searchName := c.DefaultQuery("name", "")

	hasSearch := false
	if searchUserID+searchName != "" {
		hasSearch = true
	}

	offset := 0
	limit := 0
	limit = pageSize
	if currentPage > 1 {
		offset = (currentPage - 1) * limit
	}

	objs, err := models.GetJobScriptAll()
	if err != nil {
		sc.Logger.Error("获取脚本列表失败", zap.Error(err))
		common.ReqBadFailWithMessage("获取脚本列表失败", c)
		return
	}

	allIds := []int{}
	for _, obj := range objs {
		obj := obj
		if searchName != "" && obj.Name != searchName {
			continue
		}

		if searchUserID != "" && int(obj.UserID) != searchUserIDInt {
			continue
		}
		allIds = append(allIds, int(obj.ID))
	}

	if len(allIds) == 0 {
		common.OkWithDetailed(allIds, "ok", c)
		return
	}
	objs, err = models.GetJobScriptByIdsWithLimitOffset(allIds, limit, offset)
	if err != nil {
		sc.Logger.Error("获取脚本列表失败", zap.Any("ids", allIds), zap.Error(err))
		common.ReqBadFailWithMessage("获取脚本列表失败", c)
		return
	}

	for _, obj := range objs {
		obj := obj
		obj.FillFrontAllData()
	}

	var total int
	if !hasSearch {
		total = models.GetProcessCount()
	} else {
		total = len(allIds)
	}

	resp := &ResponseResourceCommon{
		Total: total,
		Items: objs,
	}

	common.OkWithDetailed(resp, "ok", c)
}

func getJobExecScriptSelect(c *gin.Context) {
	sc := c.MustGet(common.GIN_CTX_CONFIG_CONFIG).(*config.ServerConfig)
	objs, err := models.GetJobScriptAll()
	if err != nil {
		sc.Logger.Error("获取脚本列表失败", zap.Error(err))
		common.ReqBadFailWithMessage("获取脚本列表失败", c)
		return
	}

	res := []CommonSelectResponse{}
	for _, obj := range objs {
		obj := obj
		one := CommonSelectResponse{
			Label: obj.Name,
			Value: fmt.Sprintf("%d", obj.ID),
		}
		res = append(res, one)
	}

	common.OkWithDetailed(res, "ok", c)
}

func getJobExecScriptOne(c *gin.Context) {
	sc := c.MustGet(common.GIN_CTX_CONFIG_CONFIG).(*config.ServerConfig)
	id := c.Param("id")
	intVar, _ := strconv.Atoi(id)
	dbObj, err := models.GetJobScriptById(intVar)
	if err != nil {
		sc.Logger.Error("获取脚本失败", zap.Any("id", id), zap.Error(err))
		common.ReqBadFailWithMessage("获取脚本失败", c)
		return
	}
	common.OkWithDetailed(dbObj, "ok", c)
}

func deleteJobExecScript(c *gin.Context) {
	sc := c.MustGet(common.GIN_CTX_CONFIG_CONFIG).(*config.ServerConfig)
	id := c.Param("id")
	sc.Logger.Info("删除脚本", zap.Any("id", id))

	intVar, _ := strconv.Atoi(id)
	dbObj, err := models.GetJobScriptById(intVar)
	if err != nil {
		sc.Logger.Error("根据ID获取脚本失败", zap.Any("id", id), zap.Error(err))
		common.FailWithMessage(err.Error(), c)
		return
	}
	err = dbObj.JobScriptDelete()
	if err != nil {
		sc.Logger.Error("删除脚本失败", zap.Any("id", id), zap.Error(err))
		common.FailWithMessage(err.Error(), c)
		return
	}
	common.OkWithMessage("删除脚本成功", c)
}

func updateJobExecScript(c *gin.Context) {
	sc := c.MustGet(common.GIN_CTX_CONFIG_CONFIG).(*config.ServerConfig)
	var reqObj models.JobScript
	err := c.ShouldBindJSON(&reqObj)
	if err != nil {
		sc.Logger.Error("解析更新脚本模板请求失败", zap.Any("reqObj", reqObj), zap.Error(err))
		common.FailWithMessage(err.Error(), c)
		return
	}
	err = validate.Struct(reqObj)
	if err != nil {
		if errors, ok := err.(validator.ValidationErrors); ok {
			common.ReqBadFailWithWithDetailed(
				gin.H{
					"翻译前": err.Error(),
					"翻译后": errors.Translate(trans),
				},
				"请求出错",
				c,
			)
			return
		}
		common.ReqBadFailWithMessage(err.Error(), c)
		return
	}

	_, err = models.GetJobScriptById(int(reqObj.ID))
	if err != nil {
		sc.Logger.Error("根据ID获取脚本失败", zap.Any("脚本模板", reqObj), zap.Error(err))
		common.FailWithMessage(err.Error(), c)
		return
	}

	err = reqObj.JobScriptUpdate()
	if err != nil {
		sc.Logger.Error("更新脚本失败", zap.Any("脚本模板", reqObj), zap.Error(err))
		common.FailWithMessage(err.Error(), c)
		return
	}

	common.OkWithMessage("更新脚本成功", c)
}
